package com.itheima.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Configuration
public class SentinelConfig {


    public SentinelConfig() {

        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {

            /**
             * webflux 响应事编程
             * @param exchange
             * @param te
             * @return
             */
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable te) {

                te.printStackTrace();
                System.out.println("SentinelConfig.......");

                Map map = new HashMap();
                map.put("code", 429);
                map.put("message", "请求过快， 请稍后重试.....");

                Mono<ServerResponse> responseMono = ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        .body(Mono.just(JSON.toJSONString(map)), String.class);

                return responseMono;
            }
        });

    }


}
